<template>
  <XenPageLayout
    title="新增加班申请"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="填写加班申请信息"
        subtitle="请填写完整加班申请信息以便审批"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        :showFooter="false"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChangeWithAdjust"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @departmentPickerChange="handleDepartmentPickerChange"
        @departmentPickerOpen="handleDepartmentPickerOpen"
        @departmentPickerClose="handleDepartmentPickerClose"
        @dateTimePickerOpen="handleDateTimePickerOpen"
        @dateTimePickerClose="handleDateTimePickerClose"
        @autoCompleteChange="handleAutoCompleteChange"
        @autoCompleteSearch="handleAutoCompleteSearch"
      />
    </view>

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen || isDateTimePickerOpen"
      @action="handleFormAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch, nextTick } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useOvertimeInfo } from "./composables/useInfo";
// 导入统一事件系统
import { ResignInfoEvents } from "@/utils/eventBus";

// 动态更新表单分组，根据排班记录字段状态
const formSections = computed(() => {
  const sections = getFormSectionsByPageType("create");

  // 找到包含排班记录字段的分组并更新其状态
  sections.forEach((section) => {
    const recordField = section.fields.find(
      (field) => field.key === "recordId",
    );
    if (recordField) {
      recordField.disabled = !isScheduleRecordEnabled.value;
      recordField.placeholder = isScheduleRecordEnabled.value
        ? "请选择排班记录"
        : "请先选择员工";
    }
  });

  return sections;
});

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 时间选择器打开状态
const isDateTimePickerOpen = ref<boolean>(false);

// 排班记录字段是否可用
const isScheduleRecordEnabled = ref<boolean>(false);

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "cancel",
    label: "取消",
    type: "default" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用加班申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  createOvertime,
  search,
  getBillCode,
  autoFillCurrentUserEmployee,
} = useOvertimeInfo();

// 创建API实例
import SysDailyOvertimeRequestBillApi from "./api/index";
import type { ISearchByPersonRequest } from "./api/interface";
import { overtimeFormConfig } from "./form-config";
const api = SysDailyOvertimeRequestBillApi();

// 加载排班记录
const loadScheduleRecords = async (personId: string) => {
  if (!personId) return;

  try {
    // 构建查询参数
    const today = new Date();
    const startDate = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000)
      .toISOString()
      .split("T")[0];
    const endDate = today.toISOString().split("T")[0];

    const params: ISearchByPersonRequest = {
      PersonId: personId,
      Page: 1,
      Limit: 100,
      IsPlainText: true,
      IsEmunToString: true,
      ShiftDate: [startDate, endDate],
    };

    // 调用排班记录查询接口
    const response = await api.searchByPerson(params);

    // 处理返回的排班记录数据
    if (
      response &&
      response.Data &&
      response.Data[0] &&
      response.Data[0].Records &&
      Array.isArray(response.Data[0].Records)
    ) {
      // 过滤掉AttendanceResult为"未计算"的数据
      const filteredRecords = response.Data[0].Records.filter(
        (item: any) => item.AttendanceResult !== "未计算",
      );

      const scheduleOptions = filteredRecords.map((item: any) => ({
        value: item.ID || item.Id,
        text: `${item.ShiftDate || ""} ${
          item.AttendanceShiftGroupName || ""
        } (${item.ShiftInfo || ""})`,
      }));

      // 更新配置中的选项数据
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = scheduleOptions;
        overtimeFormConfig.recordId.options = scheduleOptions.map(
          (item: any) => item.text,
        );
      }

      // 启用排班记录字段
      isScheduleRecordEnabled.value = true;
    } else {
      // 没有排班记录
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = [];
        overtimeFormConfig.recordId.options = [];
      }
    }
  } catch (error) {
    console.error("加载排班记录失败:", error);
    uni.showToast({
      title: "加载排班记录失败",
      icon: "none",
    });
  }
};

// 计算加班时长
const calculateOvertimeHours = () => {
  if (formData.startTime && formData.endTime) {
    const startTime = new Date(formData.startTime);
    const endTime = new Date(formData.endTime);

    if (endTime > startTime) {
      const diffInMs = endTime.getTime() - startTime.getTime();
      const diffInHours = diffInMs / (1000 * 60 * 60);
      formData.overtimeHours = Math.round(diffInHours * 100) / 100; // 保留两位小数
    } else {
      formData.overtimeHours = 0;
    }
  }
};

// 调整时间到最近的整点或半点
const adjustToNearestHalfHour = (dateTime: string): string => {
  if (!dateTime) return dateTime;

  const date = new Date(dateTime);
  const minutes = date.getMinutes();

  // 根据分钟数调整到最近的整点或半点
  if (minutes < 15) {
    // 0-14分钟，调整到整点
    date.setMinutes(0);
  } else if (minutes < 45) {
    // 15-44分钟，调整到半点
    date.setMinutes(30);
  } else {
    // 45-59分钟，调整到下一个整点
    date.setMinutes(0);
    date.setHours(date.getHours() + 1);
  }

  // 秒和毫秒设为0
  date.setSeconds(0);
  date.setMilliseconds(0);

  return date.toISOString();
};

// 监听开始时间和结束时间变化，自动计算加班时长
watch(
  [() => formData.startTime, () => formData.endTime],
  () => {
    calculateOvertimeHours();
  },
  { deep: true },
);

// 时间选择变化处理（带自动调整）
const handleDateTimeChangeWithAdjust = (fieldKey: string, value: any) => {
  // 如果是开始时间或结束时间，调整到整点或半点
  if ((fieldKey === "startTime" || fieldKey === "endTime") && value) {
    const originalDate = new Date(value);
    const originalMinutes = originalDate.getMinutes();

    const adjustedTime = adjustToNearestHalfHour(value);
    const adjustedDate = new Date(adjustedTime);
    const adjustedMinutes = adjustedDate.getMinutes();

    // 只有当时间被调整时才需要特殊处理
    if (originalMinutes !== adjustedMinutes) {
      const hours = adjustedDate.getHours();
      const timeStr = `${hours.toString().padStart(2, "0")}:${adjustedMinutes
        .toString()
        .padStart(2, "0")}`;

      // 先设置原始值（确保字段有值）
      handleDateTimeChange(fieldKey, value);

      // 然后立即清空
      nextTick(() => {
        formData[fieldKey] = "";

        // 再延迟设置调整后的值
        nextTick(() => {
          setTimeout(() => {
            formData[fieldKey] = adjustedTime;

            // 显示提示
            uni.showToast({
              title: `时间已自动调整为 ${timeStr}`,
              icon: "none",
              duration: 2000,
            });
          }, 50);
        });
      });
    } else {
      // 时间已经是整点或半点，直接处理
      handleDateTimeChange(fieldKey, adjustedTime);
    }
  } else {
    // 其他字段使用原始处理函数
    handleDateTimeChange(fieldKey, value);
  }
};

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  formData[fieldKey] = value;
  pickerValues[fieldKey] = value;
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 时间选择器弹框打开处理
const handleDateTimePickerOpen = () => {
  isDateTimePickerOpen.value = true;
};

// 时间选择器弹框关闭处理
const handleDateTimePickerClose = () => {
  isDateTimePickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = async (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  if (option) {
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;

    // 如果是员工选择，自动填入员工工号、姓名、公司和部门信息，并加载排班记录
    if (fieldKey === "personId" && option.subtitle) {
      const staffNoMatch = option.subtitle.match(/工号:\s*(\S+)/);
      if (staffNoMatch) {
        formData.staffNo = staffNoMatch[1];
      }
      formData.name = option.text;

      if (option.extData) {
        formData.orgName = option.extData.orgName || "";
        formData.groupName = option.extData.groupName || "";
        pickerValues.orgId = option.extData.orgId || "";
        pickerValues.groupId = option.extData.groupId || "";
        formData.orgId = option.extData.orgId || "";
        formData.groupId = option.extData.groupId || "";
      }

      // 加载该员工的排班记录
      await loadScheduleRecords(option.value);
    }
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";

    // 如果清空员工选择，也清空排班记录
    if (fieldKey === "personId") {
      formData.staffNo = "";
      formData.name = "";
      formData.orgName = "";
      formData.groupName = "";
      formData.orgId = "";
      formData.groupId = "";
      pickerValues.orgId = "";
      pickerValues.groupId = "";

      // 清空排班记录
      formData.recordId = "";
      pickerValues.recordId = "";

      // 清空排班记录选项并禁用
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = [];
        overtimeFormConfig.recordId.options = [];
      }

      // 禁用排班记录字段
      isScheduleRecordEnabled.value = false;
    }
  }

  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  console.log("搜索:", fieldKey, query);
};

// 页面加载时获取数据
onMounted(async () => {
  await initializeOptions();

  const billCode = await getBillCode();
  if (billCode) {
    formData.billCode = billCode;
  }

  // 自动填充当前用户的员工信息
  try {
    const success = await autoFillCurrentUserEmployee();
    if (success) {
      console.log("已自动填充当前用户员工信息");
      // 自动填充成功后，启用排班记录字段并加载排班记录
      isScheduleRecordEnabled.value = true;
      if (pickerValues.personId) {
        await loadScheduleRecords(pickerValues.personId);
      }
    } else {
      console.log("未能自动填充当前用户员工信息，请手动选择");
    }
  } catch (error) {
    console.error("自动填充员工信息时发生错误:", error);
  }
});

// 图片上传处理
const handleImageUpload = async (field: any, event: any) => {
  console.log("图片上传:", field.key, event);
};

const handleImageSuccess = (_field: any, _event: any) => {};

const handleImageFail = (_field: any, _event: any) => {};

const handleImageDelete = (field: any, event: any) => {
  console.log("图片删除:", field.key, event);
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {};

const handleFileSuccess = (_field: any, _event: any) => {};

const handleFileFail = (_field: any, _event: any) => {};

const handleFileDelete = (_field: any, _event: any) => {};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "cancel":
      handleCancel();
      break;
    case "submit":
      handleSubmit();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 取消按钮
const handleCancel = () => {
  uni.navigateBack();
};

// 提交表单
const handleSubmit = async () => {
  // 提交前调整时间到整点或半点
  if (formData.startTime) {
    const adjustedStartTime = adjustToNearestHalfHour(formData.startTime);
    if (adjustedStartTime !== formData.startTime) {
      formData.startTime = adjustedStartTime;
    }
  }

  if (formData.endTime) {
    const adjustedEndTime = adjustToNearestHalfHour(formData.endTime);
    if (adjustedEndTime !== formData.endTime) {
      formData.endTime = adjustedEndTime;
    }
  }

  uni.showLoading({ title: "提交中..." });

  const response = await createOvertime();

  uni.hideLoading();

  if (response.success && response.data && response.data.ID) {
    const searchResponse = await search({});
    if (searchResponse && searchResponse.length > 0) {
      ResignInfoEvents.emit("refresh", {
        id: response.data.ID,
        data: searchResponse,
        customAction: "add",
      });
    }

    uni.showToast({
      title: "提交成功",
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
    });
  } else {
    let errorMessage = "提交失败，请重试";

    if (response.error) {
      errorMessage = response.error;
    } else if (response.validation?.firstErrorMessage) {
      errorMessage = response.validation.firstErrorMessage;
    }

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000,
    });
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}
</style>
